import 'dart:math';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bmap_plugin/flutter_bmap_plugin.dart';
import 'dart:io';
import 'package:flutter/services.dart';
import 'package:vehicle_management/config/Config.dart';
import 'package:vehicle_management/public.dart';

//车辆轨迹
// ignore: must_be_immutable
class TrajectoryMapPage extends StatefulWidget {
  Map arguments;
  TrajectoryMapPage({Key key, this.arguments}) : super(key: key);

  // @override
  // _TrajectoryMapPageState createState() => _TrajectoryMapPageState(arguments: this.arguments);

  @override
  State<StatefulWidget> createState() =>
      _TrajectoryMapPageState(arguments: this.arguments);
}

class _TrajectoryMapPageState extends State<TrajectoryMapPage>
    with WidgetsBindingObserver {
  FlutterBMapViewController _controller;
  BDLocationClient _locationClient;
  static String appKey;

  Map arguments;
  var carNos = "";

  List<LatLng> _latLngList = [];

  _TrajectoryMapPageState({this.arguments}) {
    print("数据：" + arguments['datas'].toString());
  }

  @override
  void initState() {
    super.initState();
    carNos = arguments['datas']['vehicleNo'];
    appKey = preferences.getString("appKey");
    WidgetsBinding.instance.addObserver(this);
    _controller = FlutterBMapViewController();
    _locationClient = BDLocationClient();
    _locationClient.onReceiveLocation.listen((location) {
      print("经纬度:${location.latitude},${location.longitude}");
      _controller.animateMapStatusNewLatLng(
          LatLng(latitude: location.latitude, longitude: location.longitude));
      _addLocMarker(
          LatLng(latitude: location.latitude, longitude: location.longitude));
    });
    _controller.onMarkerClick.listen((Marker marker) async {
      var extraInfo = marker.extraInfo;
      var name = extraInfo['name'];
      var address = extraInfo['address'];
      print(marker.asJson());
      //var infoWindow = InfoWindow(position: marker.position, info: "$name\n$address");
      //_controller.showInfoWindow(infoWindow);
      _controller.animateMapStatusNewLatLng(marker.position);
    });
    _controller.onMapClick.listen((LatLng latLng) async {
      //_controller.hideInfoWindow();
      print(latLng.asJson());
    });
    _controller.onMapLongClick.listen((LatLng latLng) async {
      print(latLng.asJson());
    });
    _controller.onMapDoubleClick.listen((LatLng latLng) async {
      print(latLng.asJson());
    });
    _controller.onMapPoiClick.listen((MapPoi poi) async {
      print(poi.asJson());
    });
    _getCartLoc();
    // _getCaGuiJi();
  }

  void _addLocMarker(LatLng latLng) {
    _controller.clearMap();
    List<MarkerOptions> markers = [];
    var option = MarkerOptions(
      // zIndex: 160,
      position: latLng,
      icon: Platform.isAndroid ? "images/map/marker_car.png" : "Marker_car.png",
    );
    markers.add(option);
    _controller.addMarkerOverlays(markers);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("车辆位置"),
      ),
      body: FlutterBMapView(
          controller: _controller, onBMapViewCreated: _onBMapViewCreated),
    );
  }

  /// 获取车辆坐标
  _getCartLoc() async {
    var apiUrl =
        "${Config.monitorLocation}?carNos=$carNos&taskStatus=1&isDelete=0&appKey=$appKey";
    print("车辆坐标:" + apiUrl);
    var response = await Dio().get(apiUrl);
    //[{"carNo":"冀J7V523","pos":null,"tel":"18399999999","point":{"lat":38.168904,"lng":116.163537}}]
    print((response.data)['data']);
    var res = (response.data)['data'];
    //获取车辆（可编写添加车按钮（可点击切换车辆坐标））
    if (res != null) {
      for (var item in res) {
        var carCode = item["carNo"];
        print("车辆" + carCode.toString());
      }
    }
    //展示首个 (车坐标)
    setState(() {
      if (res != null) {
        var item = res[0];
        if (item["point"] != null) {
          _controller.animateMapStatusNewLatLng(LatLng(
              latitude: item["point"]["lat"], longitude: item["point"]["lng"]));
          _addLocMarker(LatLng(
              latitude: item["point"]["lat"], longitude: item["point"]["lng"]));
        }
      }
    });
  }

  ///获取车辆轨迹接口
  _getCaGuiJi() async {
    var apiUrl =
        "${Config.monitorTrail}?$carNos&taskStatus=1&isDelete=0&appKey=$appKey";
    print(apiUrl);
    var response = await Dio().get(apiUrl);
    print("车辆轨迹");
    //{京A32321: [{lat: 39.900988, lng: 116.425541}, {lat: 39.876933, lng: 116.467581}, {lat: 39.871949, lng: 116.465497}, {lat: 39.868516, lng: 116.461401}, {lat: 39.864196, lng: 116.466647}, {lat: 39.854504, lng: 116.478145}, {lat: 39.848244, lng: 116.485044}, {lat: 39.856608, lng: 116.492087}]}
    print((response.data)['data']);
    Map res = (response.data)['data'];
    setState(() {
      for (var key in res.keys) {
        print(key); //车牌号
        for (var item in res[key]) {
          //轨迹集合
          this
              ._latLngList
              .add(LatLng(latitude: item['lat'], longitude: item['lng']));
        }
      }
      //绘制轨迹
      _addPolylineOptions();
    });
  }

  @override
  void dispose() {
    super.dispose();
    WidgetsBinding.instance.removeObserver(this);
    _locationClient.dispose();
    _stopLocation();
    _locationClient.dispose();
    _controller.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print("didChangeAppLifecycleState:resume");
        _controller.setMapViewResume();
        break;
      case AppLifecycleState.inactive:
        //print("didChangeAppLifecycleState:inactive");
        break;
      case AppLifecycleState.paused:
        print("didChangeAppLifecycleState:pause");
        _controller.setMapViewPause();
        break;
      default:
        break;
    }
  }

  //开始定位
  void _startLocation() async {
    try {
      var options = LocationClientOption(
          coorType: CoorType.bd09ll, prodName: "Flutter Plugin Test");
      await _locationClient.startLocation(options);
    } on PlatformException catch (e) {
      print(e);
    }
  }

  // //单次定位
  // void _requestLocation() async {
  //   try {
  //     var options = LocationClientOption(
  //         coorType: CoorType.bd09ll, prodName: "Flutter Plugin Test");
  //     await _locationClient.requestLocation(options);
  //   } on PlatformException catch (e) {
  //     print(e);
  //   }
  // }

  //停止定位
  void _stopLocation() async {
    try {
      if (await _locationClient.isStart()) {
        await _locationClient.stopLocation();
      }
    } on PlatformException catch (e) {
      print(e);
    }
  }

  //添加点标注
  void _addMarkers() {
    List<MarkerOptions> markers = [];
    for (var index = 0; index < _latLngList.length; index++) {
      var option = MarkerOptions(
          zIndex: 100,
          position: _latLngList[index],
          title: "P$index",
          subtitle: "马塍路文三路口东部软件园创新大厦A-302",
          icon: Platform.isAndroid ? "images/map/marker.png" : "marker.png",
          extraInfo: {'name': "P$index", 'address': "马塍路文三路口东部软件园创新大厦A-302"});
      markers.add(option);
    }
    markers.first.icon =
        Platform.isAndroid ? "images/map/Icon_start.png" : "Icon_start.png";
    markers.last.icon =
        Platform.isAndroid ? "images/map/Icon_end.png" : "Icon_end.png";
    _controller.addMarkerOverlays(markers);
  }

  //画路径
  void _addPolylineOptions() {
    var customTextureList = [
      Platform.isAndroid
          ? "images/map/Icon_road_blue_arrow.png"
          : "Icon_road_blue_arrow.png",
      Platform.isAndroid
          ? "images/map/Icon_road_green_arrow.png"
          : "Icon_road_green_arrow.png",
      Platform.isAndroid
          ? "images/map/Icon_road_red_arrow.png"
          : "Icon_road_red_arrow.png",
      Platform.isAndroid
          ? "images/map/Icon_road_yellow_arrow.png"
          : "Icon_road_yellow_arrow.png"
    ];
    var intRandom = Random();
    var textureIndex = <int>[];
    for (var index = 0; index < _latLngList.length - 1; index++) {
      textureIndex.add(intRandom.nextInt(customTextureList.length));
    }
    var extraInfo = const <String, dynamic>{
      'name': "Polyline",
      'anything': "..."
    };
    var texturePolyline = TexturePolylineOptions(
        _latLngList, customTextureList, textureIndex,
        extraInfo: extraInfo);
    print(">>>>>>>>>>>>>>");
    print(texturePolyline.asJson());
    _controller.addTexturePolyline(texturePolyline);
    print(">>>>>>>>>>>>>>");
  }

  //事件
  void _onBMapViewCreated() {
    ///调用MapView.onResume()
    // _controller.setMapViewResume();
    // _startLocation(); //直接开始定位
  }
}
